package org.xxpay.pay.channel.slzfbpay;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.PayDigestUtil;
import org.xxpay.core.common.util.XXPayUtil;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.mq.BaseNotify4MchPay;

import java.net.URLEncoder;
import java.util.Base64;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author: pangxiaoyu
 * @date: 20/12/07
 */
@Service
public class SlzfbpayPaymentService extends BasePayment {

    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(SlzfbpayPaymentService.class);

    @Override
    public String getChannelName() {
        return SlzfbpayConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        return doPay(payOrder);
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    public AbstractRes doPay(PayOrder payOrder) {
        SlzfbpayConfig slzfbpayConfig = new SlzfbpayConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        DBApplicationConfig dbConfig = getDBApplicationConfig();
        Map<String, Object> paramMap = new TreeMap();

        // 接口类型
        String money = AmountUtil.convertCent2Dollar(payOrder.getAmount() + "");
        String payType = "alipay";

        paramMap.put("merchantId", slzfbpayConfig.getMchId());
        paramMap.put("payType", payType);
        paramMap.put("orderNo", payOrder.getPayOrderId());
        paramMap.put("money", money);
        paramMap.put("notifyUrl", super.getNotifyUrl(getChannelName(), dbConfig));  // 回调地址
        paramMap.put("sign", SlzfbUtil.getSign(paramMap, slzfbpayConfig.getKey()));
        try {

            String reqUrl = slzfbpayConfig.getReqUrl() + "?" + XXPayUtil.genUrlParams(paramMap);

            //这里是外部拉单服务器，
            Base64.Encoder encoder = Base64.getEncoder();
            String getOrderUrl = slzfbpayConfig.getJumpUrl()+"?url=" + encoder.encodeToString(reqUrl.getBytes())
                    + "&orderId=" + payOrder.getPayOrderId() + "&amount=" + money + "&returnUrl="
                    + URLEncoder.encode(super.getReturnUrl(getChannelName(), dbConfig),"UTF-8");
            _log.info("最终拉单连接:" + getOrderUrl);
            // 请求地址
            _log.info("{}请求路径:{}, 请求参数:{}", getChannelName(), getOrderUrl, paramMap);
            retObj.setPayJumpUrl(getOrderUrl);      // 可以通过该地址跳转到支付中心界面完成支付(URL)
            StringBuffer payForm = new StringBuffer();
            payForm.append("<script>window.location.href = '"+getOrderUrl+"';</script>");
            retObj.setPayUrl(payForm.toString());
            retObj.setPayMethod(PayConstant.PAY_METHOD_FORM_JUMP);
            int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
            _log.info("[{}]更新订单状态为支付中:payOrderId={},payUrl={},payType={},result={}", getChannelName(), payOrder.getPayOrderId(), getOrderUrl, payType, updateCount);
            return retObj;
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("操作失败!");
        }
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        return QueryRetMsg.waiting();  //支付中
    }
}
